package interactive.states
{
	import events.GestureEvent;
	
	import flash.events.TimerEvent;
	import flash.geom.Point;
	
	import global.Managers;
	
	import interactive.GestureManager;
	
	import utils.EnterFrameTimer;

	/**
	 *
	 * 触摸状态
	 * 
	 * 1. 停留时间已超过手势最大延迟，变为移动状态；
	 * 2. 当移动距离不大于手势最小移动距离且在手势最大延迟前离开，
	 * 变为等待单击状态；
	 * 3. 当移动距离大于手势最小移动距离且不大于手势最大移动距离，
	 * 且在手势延迟计时前离开屏幕时变为等待手势状态；
	 * 4. 当移动距离大于手势最大移动距离时变为移动状态；
	 * 
	 * @author Raykid
	 * 
	 */
	public class TouchState implements IGestureState
	{
		private var _lastPoint				: Point;
		private var _timerHandMax			: EnterFrameTimer;
		
		public function TouchState()
		{
			_lastPoint = new Point();
			
			_timerHandMax = new EnterFrameTimer(GestureManager.HAND_DELAY_MAX, 1);
			_timerHandMax.addEventListener(TimerEvent.TIMER_COMPLETE, timerHandMaxCompleteHandler);
		}
		private function timerHandMaxCompleteHandler(event:TimerEvent):void
		{
			// 1. 停留时间已超过手势最大延迟，变为移动状态
			var manager:GestureManager = Managers.gestureManager;
			manager.switchState(manager.moveState, _lastPoint);
		}

		public function backIn(manager:GestureManager, point:Point):void {
			// 无操作
		}
		public function switchIn(manager:GestureManager, point:Point):void
		{
			_lastPoint.x = point.x;
			_lastPoint.y = point.y;
			_timerHandMax.start();
			// 触发触摸事件
			manager.downDispatcher.dispatchEvent(new GestureEvent(GestureEvent.TOUCH, manager.downTarget, true, false, point.x, point.y));
		}
		public function switchOut(manager:GestureManager, point:Point):void
		{
			_timerHandMax.reset();
		}
		public function touch(manager:GestureManager, point:Point):void
		{
			// 无操作
		}
		public function leave(manager:GestureManager, point:Point):void
		{
			var distance:Number = Point.distance(_lastPoint, point);
			if(distance <= GestureManager.HAND_DISTANCE_MIN) {
				// 2. 当移动距离不大于手势最小移动距离且在手势最大延迟前离开，变为等待单击状态
				manager.switchState(manager.waitClickState, _lastPoint);
			} else if(distance <= GestureManager.HAND_DISTANCE_MAX) {
				// 3. 当移动距离大于手势最小移动距离且不大于手势最大移动距离，且在手势延迟计时前离开屏幕时变为等待手势状态
				manager.switchState(manager.waitHandState, point);
			}
		}
		public function move(manager:GestureManager, point:Point):void {
			// 4. 当移动距离大于手势最大移动距离时变为移动状态
			var distance:Number = Point.distance(_lastPoint, point);
			if(distance > GestureManager.HAND_DISTANCE_MAX) {
				manager.switchState(manager.moveState, _lastPoint);
			}
		}
		public function toString():String {
			return "TouchState";
		}
	}
}